<?php

/**
 * Send CSME Newsletter using Cron jobs
 * @author Jose Luis Quintana <joseluisquintana20@gmail.com>
 */
// Required file


include_once '../Libraries/bootstrap.php';

include_once JLPATH_LIBRARIES . DS . 'SPDO.class.php';
include_once JLPATH_LIBRARIES . DS . 'DataBasePDO.class.php';
include_once JLPATH_LIBRARIES . DS . 'ModelBase.class.php';
include_once JLPATH_MODELS . DS . 'NewsletterModel.php';


//$nModel = new NewsletterModel();
//$nData = $nModel->getNewsletterBySent(1);
//$nData = $nData[0];
//require JLPATH_LIBRARIES . DS . "Tools" . DS . "phpmailer" . DS . "phpmailer.php";
//$mail = new PHPMailer();
//$mail->PluginDir = "";
//$mail->IsHTML(TRUE);
//$mail->CharSet = "utf-8";
//$mail->IsMail();
//$mail->Timeout = 12;
//$mail->From = "newsletter@csme.fr";
//$mail->FromName = "Club Sportif Multisections d’Epinay-sur-Seine";
//$mail->Subject = "Test Cron DB Connexion";
//$mail->Body = "
//    <P>
//    ID: {$nData['int_id_newsletter']} <br>
//    NAME: {$nData['var_nom_newsletter']} <br>
//    STATE: {$nData['int_id_state']} <br>
//    </P>
//";
//$mail->AddAddress("alex@lbnstudio.fr");
//$mail->AddAddress("joseluisquintana20@gmail.com");
//$mail->Send();
//$mail->ClearAddresses();
//
//var_dump($nData);
//exit;

include_once JLPATH_LIBRARIES . DS . 'JLHelper.class.php';
include_once JLPATH_MODELS . DS . 'GalleryModel.php';
include_once JLPATH_HELPERS . DS . 'NewsletterHelper.class.php';
include_once JLPATH_LIBRARIES . DS . 'Smarty' . DS . 'Smarty.class.php';
include_once JLPATH_LIBRARIES . DS . 'Tools' . DS . 'JLTools.class.php';


define('BASE_SERVER_URL', 'http://www.csme.fr');
define('LIMIT', 6);

sendNewsletter();

function sendNewsletter() {
    include_once JLPATH_MODELS . DS . 'NewsletterModel.php';

    $nModel = new NewsletterModel();
    $nData = $nModel->getNewsletterBySent(1);
    $id_newsletter = $nData[0]['int_id_newsletter'];
    $var_nom_newsletter = $nData[0]['var_nom_newsletter'];
    $TEMPLATE = "";

    if (empty($nData)) {
        echo 'Ninguna newsletter para enviar !';
        exit;
    } else {
        $TEMPLATE = getNewsletterBase($id_newsletter, FALSE);
    }

    $SUBJECT = "CSME Newsletter - " . getDataFrance();

    require JLPATH_LIBRARIES . DS . "Tools" . DS . "phpmailer" . DS . "phpmailer.php";
    $mail = new PHPMailer();
    $mail->PluginDir = "";
    $mail->IsHTML(TRUE);
    $mail->CharSet = "utf-8";
    $mail->IsMail();
    $mail->Timeout = 12;
    $mail->From = "newsletter@csme.fr";
    $mail->FromName = "Club Sportif Multisections d’Epinay-sur-Seine";

    include_once JLPATH_MODELS . DS . 'AffiliesModel.php';
    $affModel = new AffiliesModel();
    $affilies = $affModel->getAffilieByLimit(LIMIT, 0);

    if (!empty($affilies)) {
        $ids = array();

        foreach ($affilies as $aff) {
            $FULLNAME = $aff['var_fullname'];
            $CODE = $aff['var_code'];
            $EMAIL = $aff['var_email'];
            $id = $aff['int_id_suscriptor'];
            $ids[] = $id;

            echo '<pre>';
            var_dump($id);

            $mail->Subject = $SUBJECT;
            $mail->Body = getNewsletterByAffilie($TEMPLATE, $FULLNAME, $CODE);
            $mail->AddAddress($EMAIL);
            $mail->Send();
            $mail->ClearAddresses();
        }

        $affModel->updateAffiliesByIds($ids, 1);
    } else {
        $COUNTER = $affModel->updateAffiliesSent(0);
        $nModel->updateNewsletterSent($id_newsletter, 0);

        $mail->FromName = "Club Sportif Multisections d’Epinay-sur-Seine";
        $mail->Subject = 'Bilan d\'envoi de la newsletter : ' . $var_nom_newsletter;

        $smarty = new Smarty();
        $smarty->assign(array(
            'BASE_URL' => BASE_SERVER_URL,
            'COUNTER' => $COUNTER
        ));

        $mail->Body = $smarty->fetch(JLPATH_WEB_SITE . DS . 'images' . DS . 'mail' . DS . 'newsletter_complete.html');

        $mail->AddAddress('directeur@csme.fr');
        $mail->AddAddress('gerard.braglia@neuf.fr');
        $mail->Send();
        $mail->ClearAddresses();
    }
}

function getNewsletterByAffilie($TEMPLATE, $fullname, $code) {
    $message = str_replace("%FULLNAME%", $fullname, $TEMPLATE);
    return str_replace("%CODE%", $code, $message);
}

function getNewsletterBase($id = NULL, $for_browser = FALSE) {
    require JLPATH_MODELS . DS . "ActualiteModel.php";

    $news = new NewsletterModel();
    $smarty = new Smarty();
    $newsletter_helper = new NewsletterHelper();
    $actualites = new ActualiteModel();
    $actualites = $actualites->getGroupActualites();
    $newsletter = $news->getNewsletter($id);
    $newsletter_helper->setBaseURL(BASE_SERVER_URL);
    $newsletter_helper->setTitle($newsletter['var_nom_newsletter']);
    $newsletter_helper->setMonth(getFrenchMonth());
    $news = $news->getActualitesBoxByIdNewsLetter($id);
    $columns = array();

    foreach ($news as $value) {
        if ($value['var_column'] == 'col01') {
            $columns[1][] = $value;
        } else {
            $columns[2][] = $value;
        }
    }

    $groupmonth = array();
    $ord = 1;

    foreach ($actualites as $row) {
        $groupmonth[$row['var_monthyear']] = $ord;
        $ord++;
    }

    $newsletter_helper->setMonthActualites($groupmonth);
    $date = getDataFrance(FALSE);
    $smarty->assign(array(
        'BASE_URL' => BASE_SERVER_URL,
        'DATE' => $date,
        'NEWSLETTER' => $newsletter,
        'NEWS1' => $columns[1],
        'NEWS2' => $columns[2],
        'BROWSER' => $for_browser,
        'HELPER' => $newsletter_helper
    ));

    return $smarty->fetch(JLPATH_WEB_SITE . DS . 'images' . DS . 'mail' . DS . 'newsletter.html');
}

function getDataFrance($fulldate = TRUE) {
    $_month = array("Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre");
    $_year = date("Y");

    if ($fulldate) {
        $_days = array("Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche");
        $fecha = "le " . $_days[intval(date("N")) - 1] . " " . date("j") . " " . $_month[intval(date("n")) - 1] . " " . $_year;
    } else {
        $fecha = $_month[intval(date("n")) - 1] . " " . $_year;
    }

    return $fecha;
}

function getFrenchMonth() {
    $_month = array("Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre");
    return $_month[intval(date("n")) - 1];
}
